#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 版权所有 (c) 2025   保留所有权利。
 * CLR版本：4.0.30319.42000
 * 机器名称：DESKTOP-GLJ2Q8J
 * 公司名称：
 * 命名空间：VSIXProjectGit.Config
 * 唯一标识：85e23a3e-9184-4a14-914e-c79024283098
 * 文件名：ReminderService
 * 当前用户域：DESKTOP-GLJ2Q8J
 * 
 * 创建者： Guo_79991
 * 电子邮箱：799919859@qq.com
 * 创建时间：2025/9/25 11:44:32
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>

// ReminderService.cs
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Threading;

namespace VSIXProjectGit
{
    public class ReminderService : IDisposable
    {
        private Timer _timer;
        private ReminderConfig _config;
        private bool _isRunning = false;

        public static ReminderService Instance { get; } = new ReminderService();

        private ReminderService()
        {
            _config = ReminderConfig.Load();
            if (_config.IsEnabled)
            {
                Start();
            }
        }

        public void Start()
        {
            if (_isRunning) return;

            _config.IsEnabled = true;
            _config.Save();

            _timer = new Timer(ShowReminder, null,
                TimeSpan.FromMinutes(_config.IntervalMinutes),
                TimeSpan.FromMinutes(_config.IntervalMinutes));

            _isRunning = true;

            ShowStatusMessage("喝水提醒已启动");
        }

        public void Stop()
        {
            if (!_isRunning) return;

            _config.IsEnabled = false;
            _config.Save();

            _timer?.Dispose();
            _timer = null;
            _isRunning = false;

            ShowStatusMessage("喝水提醒已关闭");
        }

        public void UpdateConfig(ReminderConfig newConfig)
        {
            var wasRunning = _isRunning;

            if (wasRunning)
                Stop();

            _config = newConfig;
            _config.Save();

            if (wasRunning || _config.IsEnabled)
                Start();
        }

        public ReminderConfig GetConfig() => _config;

        private void ShowReminder(object state)
        {
            ThreadHelper.JoinableTaskFactory.Run(async () =>
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                // 在VS状态栏显示提醒
                //await VS.StatusBar.ShowMessageAsync(_config.Message);
                ShowStatusMessage(_config.Message);

                // 可选：显示消息框（可能会干扰工作）
                // await VS.MessageBox.ShowAsync(_config.Message);
            });
        }

        //private void ShowStatusMessage(string message)
        //{
        //    ThreadHelper.JoinableTaskFactory.Run(async () =>
        //    {
        //        await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
        //        await VS.StatusBar.ShowMessageAsync(message);
        //    });
        //}


        private CancellationTokenSource _statusMessageCts;

        private async void ShowStatusMessage(string message, int displaySeconds = 10)
        {
            // 取消之前的消息显示
            _statusMessageCts?.Cancel();
            _statusMessageCts = new CancellationTokenSource();

            var cancellationToken = _statusMessageCts.Token;

            try
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

                // 显示初始消息
                string originalMessage = message;
                await VS.StatusBar.ShowMessageAsync(message);

                if (displaySeconds > 0)
                {
                    // 启动倒计时任务
                    _ = Task.Run(async () =>
                    {
                        for (int i = displaySeconds; i > 0; i--)
                        {
                            if (cancellationToken.IsCancellationRequested)
                                break;

                            // 每秒更新一次倒计时
                            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
                            await VS.StatusBar.ShowMessageAsync($"{originalMessage} ({i}s)");

                            await Task.Delay(1000, cancellationToken);
                        }

                        if (!cancellationToken.IsCancellationRequested)
                        {
                            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
                            await VS.StatusBar.ShowMessageAsync(""); // 清空消息
                        }
                    }, cancellationToken);
                }
            }
            catch (OperationCanceledException)
            {
                // 任务被取消是正常情况
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"状态栏消息显示失败: {ex.Message}");
            }
        }

        public void Dispose()
        {
            Stop();
        }
    }
}